package fm.dongman.modellib;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

/**
 * 上传文件
 * Created by KUIGE on 2017/11/26.
 */

public class PostFileHelper {
    //持有实例
    private static PostFileHelper SINGLETON;

    public static PostFileHelper getInstance() {
        if (SINGLETON == null) {
            SINGLETON = new PostFileHelper();
        }
        return SINGLETON;
    }

    private PostFileHelper() {
    }


    /**
     * @param parseUrl api上传接口
     * @param dir      文件路径
     */
    public JSONObject uploadMultiFile(String parseUrl, Bitmap bitmap, String dir, String token) {
        dir = Environment.getExternalStorageDirectory().getAbsolutePath() + dir;
        JSONObject jsonObject = null;
        saveMyBitmap(bitmap, dir);
        File file = new File(dir, "test.jpg");
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("upload_image", "test", fileBody)
                .build();
        Request request;
        if (token != null) {
            request = new Request.Builder()
                    .url(parseUrl)
                    .header("x-token", token)
                    .post(requestBody)
                    .build();
        } else {
            request = new Request.Builder()
                    .url(parseUrl)
                    .post(requestBody)
                    .build();
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        try {
            Response response = okHttpClient.newCall(request).execute();
            jsonObject = new JSONObject(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }
        return RemoteHelper.Companion.getInstance().connect(jsonObject, parseUrl);
    }

        private boolean fileIsExists(String dir) {
            try {
                File f = new File(dir + "test.jpg");
                if (!f.exists()) {
                    return false;
                }

            } catch (Exception e) {
                return false;
            }
            return true;
        }

    /**
     * @param bitmap 将bitmap保存到本地
     * @param dir    图片路径
     */
    private void saveMyBitmap(Bitmap bitmap, String dir) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) // 判断是否可以对SDcard进行操作
        {    // 获取SDCard指定目录下
            File dirFile = new File(dir);  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            //文件夹有啦，就可以保存图片啦
            // 在SDcard的目录下创建图片文,以当前时间为其命名
            File file = new File(dir, "test.jpg");

            FileOutputStream out = null;
            try {
                out = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
